<template>
  <div>
    <component v-if="validComponent" :is="getComponent(command)" :param="param" />
    <span v-else>无法支持的动态组件</span>
  </div>
</template>
<script setup lang="ts">
import { defineProps, onMounted, defineAsyncComponent, ref } from "vue";

interface Props {
  param: any; // 参数
  command: string;
}

const validComponent = ref(false);
const props = defineProps<Props>();

const components = import.meta.glob("./components/*.vue");

// 将组件名称和组件模块映射起来
const componentMap = new Map<string, any>();
for (const path in components) {
  const componentName = path.split("/").pop()?.replace(".vue", "");
  if (componentName) {
    componentMap.set(componentName, defineAsyncComponent(components[path]));
  }
}

// 根据 command 名称获取组件
const getComponent = (name: string) => {
  return componentMap.get(name);
};

onMounted(() => {
  console.log("dynamic-component:", props.param);
  validComponent.value = componentMap.has(props.command);
});
</script>
